<?php
class IOSS_GameRecord{
	private static $table = 'core_game_record';
	private static $table_log = 'core_game_record_op_log';

	private $record;
	private function __construct($row){
	    $this->record = $row;
	}
	
	public function __get($key){
	    return $this->record[$key];
	}
	

	/**
	 * 创建game record
	 * @param object $obj
	 * @return boolean|IOSS_GameRecord
	 */
	public static function insertIgnoreRecord($obj){
		//查询account对应的user_id和上级上上级的user_id
		$userIdResult = IOSS_User::getUserIdsByAccount($obj->account);
		if(count($userIdResult) == 0) return FALSE;
		$userIdInfo = $userIdResult[0];
		$db = IOSS_DB::getInstance();
		$time = time();
		if($obj->netAmount<0){
		    $commissions_lv1 = abs($obj->netAmount)*$obj->ftpXmlP1UserReward;
		    $commissions_lv2 = abs($obj->netAmount)*$obj->ftpXmlP2UserReward;
		    $status = 0;  //玩家输了，状态0未处理
		}else{
		    $commissions_lv1 = 0;
		    $commissions_lv2 = 0;
		    $status = -1;  //玩家赢了，状态-1只做记录，不处理
		}
		$fieldArr = array(
            $userIdInfo->user_id,
            $obj->dataType,
            $obj->billNo,
            $obj->mainBillNo,
            $obj->betTime,
            $obj->netAmount,
		    $status,
            $userIdInfo->p1_user_id,
            $userIdInfo->p2_user_id,
		    $commissions_lv1,
		    $commissions_lv2,
            $obj->opId,
		    $time
        );
        $sql = 'INSERT IGNORE INTO `core_game_record` (`user_id`,`data_type`,`bill_no`,`main_bill_no`,`bet_time`,`net_amount`,`status`,`p1_user_id`,`p2_user_id`,`commissions_lv1`,`commissions_lv2`,`op_id`,`create_time`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)';
        $db->query($sql,$fieldArr);
	}
	
	/**
	 * 处理记录表中status=0未处理的记录，将提成给上级上上级后修改status=1已完成
	 * @param int $ftpXmlHandleRecordHoursAgo 处理记录表中bet_time是$ftpXmlHandleRecordHoursAgo小时前的记录状态和提成
	 */
	public static function handleRecords($ftpXmlHandleRecordHoursAgo){
	    $db = IOSS_DB::getInstance();
	    $where = array(
	        'status'=>0,
	        'bet_time <'=>strtotime("-".$ftpXmlHandleRecordHoursAgo." hours")
	    );
	    $db->select('id,p1_user_id,p2_user_id,commissions_lv1,commissions_lv2');
	    $db->from(self::$table);
	    $db->where($where);
	    $results = $db->get()->result();
	    if(count($results) == 0) return;
	    foreach ($results as $row){
	        $db->trans_start();
	        if($row->p1_user_id>0){  //有上级
	            if(!IOSS_User::updateCommissions($row->p1_user_id,$row->commissions_lv1)){
	                $db->_trans_status = FALSE;
	            }
	        }
	        if($row->p2_user_id>0){  //有上上级
	            if(!IOSS_User::updateCommissions($row->p2_user_id,$row->commissions_lv2)){
	                $db->_trans_status = FALSE;
	            }
	        }
	        //更新该条记录状态
	        if(!self::updateRecordStatus($row->id)){
	            $db->_trans_status = FALSE;
	        }
	        $db->trans_complete();
	        if($db->trans_status() !== FALSE){
	            echo "$row->id handle success<br/>";
	        }else{
	            echo "$row->id handle error<br/>";
	        }
	    }
	}
	
	/**
	 * 更新状态
	 * @param unknown $id
	 */
	public static function updateRecordStatus($id){
	    $db = IOSS_DB::getInstance();
	    $db->where('id',$id);
	    $db->update(self::$table,array('status'=>1));
	    return $db->affected_rows()>=1;
	}
	
	/**
	 * 查询操作记录日志
	 * @param string $fileName xml文件名称
	 * @return boolean 没查到、状态为0且创建时间早于10分钟返回false(false表示需要处理插入记录);否则返回true
	 */
	public static function getRecordOpLog($fileName){
	    $db = IOSS_DB::getInstance();
	    $row = $db->where('file_name',$fileName)->get(self::$table_log)->row_array();
	    if($row == null){
	        return FALSE;
	    }
	    if(($row['status'] == 0) && (time()-$row['create_time'])>600){
	        return FALSE;
	    }
	    return TRUE;
	}
	
	/**
	 * 开始处理某文件，记录操作日志
	 * @param string $fileName xml文件名称
	 * @return boolean|op_log.id
	 */
	public static function replaceIntoOpLog($fileName){
	    $db = IOSS_DB::getInstance();
	    $data = array(
	        'file_name' => $fileName,
	        'status' => 0,
	        'create_time' => time()
	    );
	    if($db->replace(self::$table_log,$data)){
	        return $db->insert_id();
	    }else{
	        return FALSE;
	    }
	}
	
	/**
	 * @param string $fileName xml文件名称
	 */
	public static function finishOpLog($fileName){
	    $db = IOSS_DB::getInstance();
	    $db->where('file_name',$fileName);
	    $db->update(self::$table_log,array('status' => 1));
	}
	
	/**
	 * 获取订单
	 * @param int $id
	 * @return Ambigous <NULL, IOSS_Order>
	 */
	public static function getById($id){
		$db = IOSS_DB::getInstance();
		$row = $db->where('id', $id)->get(self::$table)->row_array();
		return ($row == null) ? null : (new self($row));
	}
	
	/**
	 * 获取订单列表
	 * @param array $where
	 * @param number $limit
	 * @return array<IOSS_Order>
	 */
	public static function getList($where, $limit = 10){
		$db = IOSS_DB::getInstance();
		$db->where($where);
		$db->order_by('id', 'desc');
		if($limit){
			$db->limit($limit);
		}
		$rows = $db->get(self::$table)->result_array();
		return array_map(function ($row){
			return new self($row);
		}, $rows);
	}
}